<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:include="common/admin/common::common_head">
    <title>红包列表</title>
</head>
<style>
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
        -webkit-appearance: none;
    }

    input[type="number"] {
        -moz-appearance: textfield;
    }

    .data-row {
        padding: 5px 0;
    }
</style>
<link rel="stylesheet" th:href="@{/admin/assets/bootstrap-select/css/bootstrap-select.css}">
<body class="cm-no-transition cm-1-navbar">
<!--后台公共侧边栏（菜单）-->
<div th:replace="common/admin/common::common_siderbar"></div>
<!--后台公共顶部-->
<div th:replace="common/admin/common::common_top"></div>

<div id="global">
    <div class="container-fluid">
        <div class="row cm-fix-height">
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-body">
                        <h4>红包列表</h4>
                        <div style="margin: 10px 0;">
                            <div class="btn-group" role="group">
                                <button class="btn btn-turquoise save-action" type="button">
                                    <i class="fa fa-plus"></i> 添加
                                </button>
                            </div>
                        </div>
                        <table class="table table-bordered table-hover" id="data-show-table">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>红包名称</th>
                                <th>兑换码</th>
                                <th>剩余个数</th>
                                <th>红包类型</th>
                                <th>开始时间</th>
                                <th>结束时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div aria-hidden="true" aria-labelledby="myModalLabel" class="modal fade" id="myModal" role="dialog" tabindex="-1">
        <div aria-hidden="true" class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel">
                        红包详细
                    </h4>
                </div>
                <div class="modal-body">
                    <div id="hint"></div>
                    <div id="data-show">
                        <div class="row data-row text1-box">
                            <div class="col-xs-3 text-center">红包名称：</div>
                            <div class="col-xs-9 text1">0.0</div>
                        </div>
                        <div class="row data-row text2-box">
                            <div class="col-xs-3 text-center">红包详细：</div>
                            <div class="col-xs-9 text2">0.0</div>
                        </div>
                        <div class="row data-row text3-box">
                            <div class="col-xs-3 text-center">兑换码：</div>
                            <div class="col-xs-9 text3">0.0</div>
                        </div>
                        <div class="row data-row text4-box">
                            <div class="col-xs-3 text-center">总个数：</div>
                            <div class="col-xs-9 text4">0.0</div>
                        </div>
                        <div class="row data-row text5-box">
                            <div class="col-xs-3 text-center">使用方法：</div>
                            <div class="col-xs-9 text5">0.0</div>
                        </div>
                        <div class="row data-row text6-box">
                            <div class="col-xs-3 text-center">红包类型：</div>
                            <div class="col-xs-9 text6">0.0</div>
                        </div>
                        <div class="row data-row text7-box">
                            <div class="col-xs-3 text-center">项目类型：</div>
                            <div class="col-xs-9 text7">0.0</div>
                        </div>
                        <div class="row data-row text8-box">
                            <div class="col-xs-3 text-center">开始时间：</div>
                            <div class="col-xs-9 text8">0.0</div>
                        </div>
                        <div class="row data-row text9-box">
                            <div class="col-xs-3 text-center">结束时间：</div>
                            <div class="col-xs-9 text9">0.0</div>
                        </div>
                        <div class="row data-row text10-box">
                            <div class="col-xs-3 text-center">状态：</div>
                            <div class="col-xs-9 text10">0.0</div>
                        </div>
                    </div>
                    <div id="add-form-box">
                        <form class="form-horizontal" id="actionForm">
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="rname">红包名称：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <input class="form-control" id="rname" maxlength="30" name="rname" placeholder="请输入红包名称" required type="text">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="describe">红包介绍：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <input class="form-control" id="describe" maxlength="255" name="describe" placeholder="请输入红包介绍" required type="text">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">红包类型：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <div class="radio">
                                            <label th:each="rtype : ${rtypeMap}">
                                                <input name="rtype" th:checked="${rtypeStat.first}" th:class="|radio-${rtype.key}|"
                                                       th:value="${rtype.key}" type="radio">
                                                <span th:utext="(${rtype.value} + '&emsp;')"></span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group" id="threshold-box" style="display: none;">
                                <label class="col-sm-2 control-label" for="threshold">门槛金额：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <span class="input-group-addon">￥</span>
                                        <input class="form-control" id="threshold" name="threshold" placeholder="请输入门槛金额" required type="number" value="0">
                                        <span class="input-group-addon">.00</span>
                                        <div class="input-group-btn">
                                            <button aria-label="Help" class="btn btn-default tooltip-test" data-title="门槛金额必须大于0" data-toggle="tooltip"
                                                    type="button">
                                                <span class="glyphicon glyphicon-question-sign"></span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="amount">抵扣金额：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <span class="input-group-addon">￥</span>
                                        <input class="form-control" id="amount" name="amount" placeholder="请输入抵扣金额" required type="number" value="0">
                                        <span class="input-group-addon">.00</span>
                                        <div class="input-group-btn">
                                            <button aria-label="Help" class="btn btn-default tooltip-test" data-title="抵扣金额必须大于0" data-toggle="tooltip"
                                                    type="button">
                                                <span class="glyphicon glyphicon-question-sign"></span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group" id="ptype-box" style="display: none;">
                                <label class="col-sm-2 control-label" for="ptype">项目类型：</label>
                                <div class="col-sm-10">
                                    <select class="selectpicker" id="ptype" name="ptype">
                                        <option th:each="ptype : ${ptypeMap}" th:if="${ptypeStat.count > 1}" th:text="${ptype.value}"
                                                th:value="${ptype.key}"></option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="number">红包个数：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <input class="form-control" id="number" name="number" placeholder="请输入红包个数" required type="number">
                                        <div class="input-group-btn">
                                            <button aria-label="Help" class="btn btn-default tooltip-test" data-title="红包个数必须大于0" data-toggle="tooltip"
                                                    type="button">
                                                <span class="glyphicon glyphicon-question-sign"></span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="startTime">开始时间：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <input class="form-control" id="startTime" name="startTimeStr" placeholder="请选择开始时间" required
                                               th:min="${minTime}"
                                               type="datetime-local">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="endTime">结束时间：</label>
                                <div class="col-sm-10">
                                    <div class="input-group">
                                        <input class="form-control" id="endTime" name="endTimeStr" placeholder="请选择开始时间" required th:min="${minTime}"
                                               type="datetime-local">
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-default" data-dismiss="modal" type="button">取消</button>
                    <button class="btn btn-primary" id="submitBtn" type="button">确定</button>
                </div>
            </div>
        </div>
    </div>

    <footer th:replace="common/admin/common::common_footer"></footer>
</div>

<script th:replace="common/admin/common::common_footer_script"></script>
<script th:src="@{/admin/assets/bootstrap-select/js/bootstrap-select.js}" type="text/javascript"></script>
<script th:src="@{/admin/assets/layer/layer.js}" type="text/javascript"></script>
<script th:src="@{/admin/assets/js/datetime.js}" type="text/javascript"></script>
<script th:src="@{/admin/assets/js/demo/popovers-tooltips.js}" type="text/javascript"></script>
<script type="text/javascript">
    document.title = '亿人宝 - 红包列表';
    const get_action = 'get';
    // 红包类型
    const rtypeMap = {
        1: '[[${rtypeMap.get(1)}]]',
        2: '[[${rtypeMap.get(2)}]]',
        3: '[[${rtypeMap.get(3)}]]',
        4: '[[${rtypeMap.get(4)}]]',
        5: '[[${rtypeMap.get(5)}]]'
    };
    // 状态类型
    const stateMap = {
        1: '[[${stateMap.get(1)}]]',
        2: '[[${stateMap.get(2)}]]'
    };
    // 项目类型
    const ptypeMap = {
        1: '[[${ptypeMap.get(1)}]]',
        2: '[[${ptypeMap.get(2)}]]',
        3: '[[${ptypeMap.get(3)}]]',
        4: '[[${ptypeMap.get(4)}]]'
    };

    // layer的loading层
    function load() {
        return layer.load(0, {
            offset: ['50%', '50%']
        });
    }

    /**
     * 传入list，得到html字符串
     * @param list
     */
    function splitListForTableString(list) {
        function createTd(tdContent, title) {
            if (undefined !== title) {
                return "<td title='" + title + "'>" + (null == tdContent ? "" : tdContent) + "</td>";
            } else {
                return "<td>" + (null == tdContent ? "" : tdContent) + "</td>";
            }
        }

        let str = "";

        let curr = null;
        for (let i = 0; i < list.length; i++) {
            curr = list[i];
            str += "<tr>";
            str += createTd(curr.id);
            str += createTd(curr.rname.substring(0, 8) + '...', curr.rname);
            str += createTd(curr.exchangeCode);
            str += createTd(curr.number);
            str += createTd(rtypeMap[curr.rtype]);
            str += createTd(formatDatetime(curr.startTime));
            str += createTd(formatDatetime(curr.endTime));
            str += createTd(stateMap[curr.state]);
            str += "<td>";
            str += '<div class="btn-group" role="group">';
            str += '<button class="btn btn-info get-action" data-id="' + curr.id + '" title="查看" type="button">';
            str += '<i class="fa fa-fw fa-search-plus"></i>';
            str += '</button>';
            str += '<button class="btn btn-danger remove-action" data-id="' + curr.id + '" data-name="' + curr.rname + '" title="删除" type="button">';
            str += '<i class="fa fa-fw fa-trash-o"></i>';
            str += '</button>';
            str += '</div>';
            str += "</td>";
            str += "</tr>";
        }

        return str;
    }

    // 刷新数据
    function refreshData(param) {
        param.pageSize = [[${pager.pageSize}]];
        let loadIndex = load();
        $.getJSON('[[@{/admin/redpacket/listJson}]]', param, function (data) {
            let $dataShowTable = $('#data-show-table');

            if (undefined !== data && data.status === 200) {
                let list = data.obj;

                let $tbody = $dataShowTable.find('tbody');
                $tbody.html(splitListForTableString(list));

                $('.get-action').tooltip();
                $('.remove-action').tooltip();
            }
            layer.close(loadIndex);
        })
    }

    $(function () {
        refreshData({});

        let $modal = $('#myModal');
        let $dataShowTable = $('#data-show-table');// 数据显示的表格
        let $modalLabel = $modal.find('#myModalLabel');// 模态框头部标题

        // 构建模态框信息，用户展示信息
        function buildDataForShow(o) {
            $modalLabel.text('红包【' + o['rname'] + '】的详细信息：');

            let $dataShow = $('#data-show');
            $dataShow.find('.text1-box .text1').text(o['rname']);
            $dataShow.find('.text2-box .text2').text(o['describe']);
            $dataShow.find('.text3-box .text3').text(o['exchangeCode']);
            $dataShow.find('.text4-box .text4').text(o['number'] + '个');
            let rtype = o['rtype'];// 红包类型
            if (rtype <= 2) {// 无门槛红包，无需显示
                $dataShow.find('.text5-box .text5').html('该红包可抵扣<b>' + o['amount'] + '</b>元');
                $dataShow.find('.text7-box').hide();
            } else if (rtype === 5) {// 特定项目类型红包
                $dataShow.find('.text5-box .text5').html('该红包可抵扣<b>' + o['amount'] + '</b>元');
                $dataShow.find('.text7-box').show();
                $dataShow.find('.text7-box .text7').text(ptypeMap[o['ptype']]);
            } else {
                $dataShow.find('.text5-box .text5').html('满<b>' + o['amount'] + '</b>元减<b>' + o['threshold'] + '</b>元');
                $dataShow.find('.text7-box').show();
                $dataShow.find('.text7-box .text7').text(ptypeMap[o['ptype']]);
            }
            $dataShow.find('.text6-box .text6').text(rtypeMap[rtype]);
            $dataShow.find('.text8-box .text8').text(formatDatetime(o['startTime']));
            $dataShow.find('.text9-box .text9').text(formatDatetime(o['endTime']));
            $dataShow.find('.text10-box .text10').text(stateMap[o['state']]);

            $modal.find('#hint').hide();
            $modal.find('#add-form-box').hide();
            $modal.find('#data-show').show();
        }

        // 验证数据
        function checkData() {
            // 红包名称
            let $rnameInput = $('#actionForm input[name="rname"]');
            let rnameVal = $rnameInput.val().trim();
            if ('' == rnameVal || rnameVal.length <= 0) {
                layer.msg('请填写红包名称！');
                return false;
            }
            if (rnameVal.length > 30 || rnameVal.length < 5) {
                layer.msg('红包名称长度请在5~30字之间！');
                return false;
            }
            // 红包介绍
            let $describeInput = $('#actionForm input[name="describe"]');
            let describeVal = $describeInput.val().trim();
            if ('' == describeVal || describeVal.length <= 0) {
                layer.msg('请填写红包介绍！');
                return false;
            }
            if (describeVal.length > 200) {
                layer.msg('红包介绍长度请在200字之内！');
                return false;
            }

            // 根据类型判断必选项
            let $radio34Checked = $('.radio-3:checked,.radio-4:checked');
            if ($radio34Checked.length > 0) {
                // 判断门槛金额是否有填写
                let $thresholdInput = $('input[name="threshold"]');
                let $thresholdVal = $thresholdInput.val().trim();
                if ('' == $thresholdVal || parseFloat($thresholdVal) <= 0) {
                    layer.msg('请正确填写门槛金额！');
                    return false;
                }
            }
            // 抵扣金额
            let $amountInput = $('input[name="amount"]');
            let $amountVal = $amountInput.val().trim();
            if ('' == $amountVal || $amountVal.length <= 0) {
                layer.msg('请正确填写抵扣金额！');
                return false;
            }
            // 红包个数
            let $numberInput = $('input[name="number"]');
            let $numberVal = $numberInput.val().trim();
            if ('' == $numberVal || $numberVal.length <= 0) {
                layer.msg('请正确填写红包个数！');
                return false;
            }
            // 开始时间
            let $startInput = $('input[name="startTimeStr"]');
            let $startVal = $startInput.val().trim();
            if ('' == $startVal || $startVal.length <= 0) {
                layer.msg('请正确选择开始时间！');
                return false;
            }
            // 结束时间
            let $endInput = $('input[name="endTimeStr"]');
            let $endVal = $endInput.val().trim();
            if ('' == $endVal || $endVal.length <= 0) {
                layer.msg('请正确选择结束时间！');
                return false;
            }
            return true;
        }

        // 点击查看详细
        $dataShowTable.on('click', '.get-action', function (event) {
            let $this = $(this);
            let id = $this.attr('data-id');

            let dataObj = $this.data('data-obj-' + id);
            if (undefined !== dataObj) {
                // 有缓存
                buildDataForShow(dataObj);
                $modal.find('.modal-footer').hide();
                $modal.modal('show');
            } else {
                let loadIndex = load();
                // 无缓存
                $.getJSON('[[@{/admin/redpacket/}]]' + id, {}, function (data) {
                    layer.close(loadIndex);
                    if (data.status === 200) {
                        let o = data.obj;
                        $this.data('data-obj-' + id, o);

                        buildDataForShow(o);// 数据显示
                        $modal.find('.modal-footer').hide();
                        $modal.modal('show');
                    }
                });
            }
        });

        // 点击删除
        $dataShowTable.on('click', '.remove-action', function (event) {
            let $this = $(this);
            let id = $this.attr('data-id');
            let rname = $this.attr('data-name');
            $modalLabel.text('确认删除：');
            $modal.find('#hint').text('确定要删除该红包【' + rname + '】吗');
            $modal.find('.modal-footer').show();

            $modal.find('#add-form-box').hide();
            $modal.find('#data-show').hide();
            $modal.find('#hint').show();
            $modal.modal('show');

            $('#submitBtn')[0].onclick = function () {
                let loadIndex = load();
                $.post('[[@{/admin/redpacket/remove/}]]' + id, {}, function (data) {
                    layer.close(loadIndex);

                    if (data.status === 200) {
                        layer.msg(data.msg, {time: 1000}, function () {
                            location.reload();
                        });
                    } else {
                        layer.msg(data.msg, {time: 1500});
                    }
                }, 'json');
            };
        });

        // 点击保存
        $('.save-action').on('click', function (event) {
            $modalLabel.text('添加红包：');

            $modal.find('#hint').hide();
            $modal.find('#data-show').hide();
            $modal.find('#add-form-box').show();
            $modal.find('.modal-footer').show();

            let $rnameInput = $('#actionForm input[name="rname"]');
            $rnameInput.val('');
            let $describeInput = $('#actionForm input[name="describe"]');
            $describeInput.val('');
            let $rtypeInputs = $('#actionForm input[name="rtype"]');
            $rtypeInputs.prop('checked', false);
            $($rtypeInputs[0]).prop('checked', true);
            let $thresholdInput = $('input[name="threshold"]');
            $thresholdInput.parents('.form-group').stop().hide();
            $thresholdInput.val(0);
            let $amountInput = $('input[name="amount"]');
            $amountInput.val(0);
            let $ptypeSelect = $('select[name="ptype"]');
            $ptypeSelect.parents('.form-group').stop().hide();
            $ptypeSelect.selectpicker('val', $ptypeSelect[0].options[0].value);
            let $numberInput = $('input[name="number"]');
            $numberInput.val(0);
            let $startInput = $('input[name="startTimeStr"]');
            $startInput.val('');
            let $endInput = $('input[name="endTimeStr"]');
            $endInput.val('');

            $modal.modal('show');

            $('#submitBtn')[0].onclick = function () {
                if (checkData()) {
                    // 禁用重复提交
                    $('#submitBtn').attr('disabled', 'disabled');
                    let loadIndex = load();
                    // Ajax提交添加红包
                    $.post('[[@{/admin/redpacket/save}]]', $('#actionForm').serializeArray(), function (data) {
                        layer.close(loadIndex);
                        if (data.status === 200) {
                            layer.msg(data.msg, {
                                time: 1000,
                                icon: 1
                            }, function () {
                                location.reload();
                            })
                        } else {
                            $('#submitBtn').removeAttr('disabled');
                            layer.msg(data.msg);
                        }
                    }, 'json');
                }
            }
        });

        $('#actionForm .radio-1,#actionForm .radio-2').on('change', function () {
            $('#threshold-box').stop().slideUp();
            $('#ptype-box').stop().slideUp();
        });
        $('#actionForm .radio-3').on('change', function () {
            $('#threshold-box').stop().slideDown();
            $('#ptype-box').stop().slideUp();
        });
        $('#actionForm .radio-4').on('change', function () {
            $('#threshold-box').stop().slideDown();
            $('#ptype-box').stop().slideDown();
        });
        $('#actionForm .radio-5').on('change', function () {
            $('#threshold-box').stop().slideUp();
            $('#ptype-box').stop().slideDown();
        });
    })
</script>
</body>
</html>